import random

from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.views import ObtainJSONWebToken
import re
from carts.utils import merge_cookie_redis_cart
from goods.models import SKU
from goods.serializers import HotSkuListSerializer
from orders.models import OrderInfo, OrderGoods
from orders.serializers import  OrderGetSerializer
from oauth.utils import generate_sign_openid, decode_sign_openid
from .models import User
from rest_framework.generics import GenericAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework import mixins
from . import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from django_redis import get_redis_connection
class CheckUsernameView(APIView):
    def get(self,request,username):

        #1,根据用户名查询,用户数量
        count = User.objects.filter(username=username).count()

        #2,返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class CheckMobileView(APIView):
    def get(self,request,mobile):

        #1,根据手机号查询,用户数量
        count = User.objects.filter(mobile=mobile).count()

        #2,返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class RegisterUserView(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializer

    # def post(self,request):
        #一, 只继承自了GenericAPIView
        # #1,获取参数
        # dict_data = request.data
        #
        # #2,创建序列化器,校验
        # serializer =  self.get_serializer(data=dict_data)
        # serializer.is_valid(raise_exception=True)
        #
        # #3,数据入库
        # serializer.save()
        #
        # #4,返回响应
        # return Response(serializer.data,status=status.HTTP_201_CREATED)

        #二,使用了mixin + GenericAPIView
        # return self.create(request)

class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer

    permission_classes = [IsAuthenticated] #认证的用户

    def get_object(self):
        return self.request.user

    # def get(self,request):
    #     #一, 单纯使用二级视图实现
    #     # #1,获取用户对象(或者request.user)
    #     # user =  self.get_object()
    #     #
    #     # #2,创建序列化对象
    #     # serializer = self.get_serializer(instance=user)
    #     #
    #     # #3,返回数据
    #     # return Response(serializer.data)
    #
    #     #二,二级视图配合mixin
    #     return self.retrieve(request)

class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user

    # def put(self,request):
    #     #一, 单纯使用二级视图实现
        # #1,获取数据
        # dict_data = request.data
        # user = self.get_object()
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(instance=user,data=dict_data)
        #
        # #3,校验,入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)
    #     #二,二级视图配合mixin
        # return self.update(request)

class EmailActiveView(APIView):
    def get(self,request):
        #1,获取参数token
        token = request.query_params.get("token")

        #2,为空校验
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,解密token
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #4,数据入库(修改email_active属性)
        user.email_active = True
        user.save()

        #5,返回响应
        return Response(status=status.HTTP_200_OK)

class AddressView(mixins.CreateModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  GenericViewSet):
    serializer_class = serializers.AddressSerializer

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self,request):

        # 1,获取用户地址信息
        queryset = self.get_queryset()

        #2,获取序列化器
        serializer = self.get_serializer(instance=queryset,many=True)

        #3,返回
        return Response({
            "addresses":serializer.data,
            "limit":20,
            "default_address_id":request.user.default_address_id
        })

    #1,重写地址创建方法,判断用户的地址是否已经达到20个了
    def create(self, request, *args, **kwargs):
        # #1,获取参数
        # dict_data = request.data
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(data=dict_data)
        #
        # #3,校验入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)

        #1,获取用户地址数量
        count =  request.user.addresses.filter(is_deleted=False).count()

        #2,判断地址的数量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,调用父类方法即可
        return super(AddressView, self).create(request,*args,**kwargs)

    #2,更改用户默认地址
    @action(methods=['put'],detail=True) #格式: addresses/pk/status
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)

    #3,修改地址的标题
    @action(methods=["put"],detail=True)
    def title(self,request,pk):
        #1,获取参数
        dict_data = request.data
        address = self.get_object()

        #2,创建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address,data=dict_data)

        #3,校验数据,入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        #4,返回
        return Response(serializer.data)

    #4,重写destory方法,为了逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class TestView(APIView):
    def get(self,request,name,age):
        print(self.kwargs) #获取的就是地址中,写带的资源参数
        return Response("%s,%s"%(name,age))

class UserBrowerHistoryView(CreateAPIView):
    serializer_class =serializers.UserBrowerHistorySerializer

    # def post(self,request):
    #
    #     #1,获取参数
    #     dict_data = request.data
    #
    #     #2,获取序列化器,校验
    #     serializer = self.get_serializer(data=dict_data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     #3,入库(保存到redis中)
    #     serializer.save()
    #
    #     #4,返回
    #     return Response(serializer.data)

    def get(self,request):
        #1,获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%request.user.id,0,4)

        #2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url":sku.default_image_url,
                "name":sku.name,
                "price":sku.price,
                "comments":sku.comments,
                "id":sku.id
            }
            sku_list.append(sku_dict)

        #3,返回
        return Response(sku_list)

#重写登陆类视图
class UserObtainJSONWebToken(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):

        #1,调用父类方法
        response = super().post(request, *args, **kwargs)

        #2,获取序列化器
        serializer = self.get_serializer(data=request.data)

        #3,判断是否认证成功
        if serializer.is_valid():

            #3.1获取user对象
            user = serializer.validated_data.get("user")

            #3.2合并购物车
            response = merge_cookie_redis_cart(request,user,response)

        return response

#订单
class UserOrdersView(GenericAPIView):
    # 关闭分页
    # pagination_class = None

    #需要登陆才能查看
    permission_classes = [IsAuthenticated]

    serializer_class= OrderGetSerializer



    def get(self,request):
        #获取所有订单对象
        orders = OrderInfo.objects.filter(user_id=request.user.id).all()

        #得到序列化器
        serializer=self.get_serializer(instance=orders,many=True)

        #得到订单数据列表
        order_data=serializer.data

        #遍历所有订单对象
        count=0
        for  order in order_data:
            #获取商品该订单下所有商品对象
            ordergoods=OrderGoods.objects.filter(order_id=order['order_id']).all()

            #拼接数据
            skus=[]
            #遍历所有订单商品对象
            for ordergood in ordergoods:
                #查询具体商品所有对象
                sku = SKU.objects.get(id=ordergood.sku_id)
                #序列化
                sku_serializers=HotSkuListSerializer(instance=sku)

                #拼接数据
                dict={
                    "count":ordergood.count,
                    "amount":(ordergood.count)*(ordergood.price),
                    "price":ordergood.price,
                    "sku":sku_serializers.data
                }
                skus.append(dict)

            #拼接额外数据
            order['skus'] = skus
            count=count+1

        #返回的最后数据
        data={
            "count":count,
            "results":order_data
        }

        return Response(data=data,status=status.HTTP_200_OK)





#测试gie上传

class GetName(APIView):
    def get(self,request,username):
        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                try:
                    user = User.objects.get(mobile=username)
                except:
                    user = User.objects.get(username=username)
            else:
                user = User.objects.get(username=username)
        except Exception as e:
            return Response({'message':'用户不存在'})

        dict_data = request.query_params
        print(dict_data)
        text = dict_data.get('text')
        image_code_id = dict_data.get('image_code_id')

        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get("image_code_%s"%image_code_id)

        if not redis_text:
            return Response({"message": "验证码已过期"}, status=status.HTTP_400_BAD_REQUEST)
        # if text.upper() != redis_text.decode().upper():
        #     return Response({"message":"验证码错误"},status=status.HTTP_400_BAD_REQUEST)



        mobile = user.mobile
        access_token = generate_sign_openid(mobile)
        data = {
            'mobile':mobile,
            'access_token':access_token
        }

        return Response(data)

class VerifySmscode(APIView):
    def get(self,request,username):
        a = 10
        dict_data = request.query_params
        sms_code = dict_data.get('sms_code')
        if re.match(r'^1[3-9]\d{9}$', username):
            try:
                user = User.objects.get(mobile=username)
            except:
                user = User.objects.get(username=username)
        else:
            user = User.objects.get(username=username)
        mobile = user.mobile
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            return Response({"message": "验证码已过期"}, status=status.HTTP_400_BAD_REQUEST)
        if sms_code != redis_sms_code.decode():
            return Response({"message": "验证码不正确"}, status=status.HTTP_400_BAD_REQUEST)



        access_token = generate_sign_openid(user.mobile)
        data = {
            'user_id':user.id,
            'access_token':access_token
        }
        return Response(data,status=status.HTTP_200_OK)

class Sendsmscode(APIView):
    def get(self,request):

        dict_data = request.query_params
        access_token = dict_data.get('access_token')
        mobile = decode_sign_openid(access_token)
        # 3,发送短信
        sms_code = "%06d" % random.randint(0, 99999)
        print("sms_code = %s" % sms_code)

        # 使用celery发送短信任务
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)
        redis_conn = get_redis_connection("code")
        redis_conn.setex("sms_code_%s" % mobile, 300, sms_code)

        return Response(status=status.HTTP_200_OK)

class ResetPassword(APIView):
    def post(self,request,pk):
        dict_data = request.data
        access_token = dict_data.get('access_token')
        password = dict_data.get('password')
        password2 = dict_data.get('password2')
        if not decode_sign_openid(access_token):
            return Response({"message": "你是一个坏的请求"}, status=status.HTTP_400_BAD_REQUEST)
        if password != password2:
            return Response({"message": "两次密码不一致"}, status=status.HTTP_400_BAD_REQUEST)
        user = User.objects.get(id=pk)
        user.set_password(password)
        user.save()
        return Response(status=status.HTTP_200_OK)

    # 修改密码
    def put(self,request,pk):
        user = request.user
        if user and user.is_authenticated:
            #获取参数
            old_pwd = request.data.get('old_password')
            pwd = request.data.get('password')
            pwd2 = request.data.get('password2')
            #校验参数
            if not user.check_password(old_pwd):
                return Response({'message':'原密码不正确'},status=status.HTTP_400_BAD_REQUEST)
            if pwd != pwd2:
                return Response({'message':'输入两次密码不一致'},status=status.HTTP_400_BAD_REQUEST)
            # 新密码保存
            try:
                user.set_password(pwd)
                user.save()
            except:
                return Response({'message':'数据库信息错误'},status=status.HTTP_400_BAD_REQUEST)
            return Response({'messega':'ok'})
        return Response(status=status.HTTP_403_FORBIDDEN)
